package com.aaa.tomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Teacher陈
 * @date ：Created in 2021/1/20 11:00
 * @description：AAA的tomcat
 * @modified By：
 * @version: 1
 */
public class TomcatAAA {

    /**
     * 1：通过serverSoket启动一个监听程序，监听8080端口
     * 2：socket对象可以获取inputstream请求字节流，还可以获取响应outputStream
     * 3：从请求中解析http报文，获取请求方式和请求地址
     * 4：根据请求地址获取servlet类，然后根据请求方式执行servlet中对应的逻辑处理方法
     * 5：构建响应对象，响应给浏览器
     */
    private int port = 9090;
    /**
     * 定义一个servlet映射集合，key  url   ,  value   clazz
     */
    private Map<String, String> urlServletMap = new HashMap();

    public TomcatAAA(int port) {
        this.port = port;
    }

    public TomcatAAA() {
    }

    /**
     * @return
     * @create by: Teacher陈
     * @description: 启动tomcat
     * @create time: 2021/1/20 11:04
     */
    public void start() {
        //加载所有的url和servlet的映射关系
        //urlServletMap = MyXmlUtil.loadWebXml();
        urlServletMap = MylUtil.loadServletAnn(null);
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(this.port);
            System.out.println("tomcat  is  running");
            while (true) {
                //等待客户端请求
                socket = serverSocket.accept();
                //获取客户端发送的信息
                InputStream inputStream = socket.getInputStream();
                //响应客户端的信息
                OutputStream outputStream = socket.getOutputStream();
                //构建请求和响应
                RequestAAA requestAAA = new RequestAAA(inputStream);
                ResponseAAA responseAAA = new ResponseAAA(outputStream);
                //获取servlet
                for (Map.Entry<String, String> entry : urlServletMap.entrySet()) {
                    if (entry.getKey().equals(requestAAA.getUrl())) {
                        Class<ServletAAA> servletAAAClass = (Class<ServletAAA>) Class.forName(entry.getValue());
                        ServletAAA servletAAA = servletAAAClass.newInstance();
                        servletAAA.service(requestAAA, responseAAA);
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    public static void main(String[] args) {
        TomcatAAA tomcatAAA = new TomcatAAA();
        tomcatAAA.start();
    }
}
